//
//  MHGameHotViewController.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHGameHotViewController.h"
#import "Lib.h"
#import "Contants.h"
#import "Application.h"
#import "MHGameCell.h"
#import "UIImageView+WebCache.h"
#import "MHGameHotSlider.h"

#import "MHGameListViewController.h"
#import "MHAppListViewController.h"
#import "MHNewGameAppViewController.h"
#import "MHGameDetailViewController.h"
#import "MHEventViewController.h"
#import "MHBaseViewController.h"
#import "MHGiftViewController.h"

@interface MHGameHotViewController ()
{
    
}
@property (nonatomic, strong) NSMutableArray* data;
@property (nonatomic, strong) NSMutableArray* hotData;
@property (nonatomic, strong) MHGameHotSlider* slider;
@property (nonatomic, assign) int       currentPage;

//@property (nonatomic, strong) MHNavibarView* navibarView;

@end

@implementation MHGameHotViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.currentPage = 0;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self reloadData];

//    self.navibarView = [MHNavibarView createWithLeftButton:kFileBtnHuman rightButton:nil searchButton:YES];
//    [self.navibarView setActionSelectorDelegate:self left:nil right:nil search:nil];
//    [self.view addSubview:self.navibarView];

}

//- (void)viewWillAppear:(BOOL)animated {
//    [self.tableView reloadData];
//}

- (void)refresh {
    [self.data removeAllObjects];
    self.data = nil;
    [self reloadData];
}

- (void)loadingMore {
    [self loadMore];
}

- (void)delayReload {
    [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.5];
}


- (void)reloadData {
    if (self.data) {
        return;
    }
    [Lib showLoadingView];
    [self LoadDataFromIndex:0];
}

- (void)loadMore {
    [self LoadDataFromIndex:self.currentPage];
}

- (void)LoadDataFromIndex:(int)pageIndex {
    self.isLoading = YES;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSArray* array = [Application appsFromServiceUrl:[Contants gameUrlWithGenre:0 platform:0 publisher:0 hot:1 news:0 mostView:1 pageIndex:self.currentPage pageSize:10]];
        NSString* url = [Contants gameUrlWithCategory:0 idSystem:kPlatformIos idGroup:kGroupGame isHot:1 isNew:0 mostView:0 pageIndex:pageIndex pageSize:10 key:kServerKey];
        NSArray* array = [Application appsFromServiceUrl:url];
        NSLog(@"url: %@", url);
        if (pageIndex == 0 || !self.data) {
            self.data = [NSMutableArray arrayWithArray:array];
            self.hotData = [NSMutableArray arrayWithArray:[Application getGameHot]];
        }
        else {
            for (id game in array) {
                [self.data addObject:game];
            }
        }
        self.currentPage = pageIndex + 1;;
        
        // main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self stopLoadingMore];
            [self stopLoading];
            [self.tableView reloadData];
        });
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView Source 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.data.count + 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* CellIndentifier = @"Cell";
    if (indexPath.section == 0) {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] init];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            self.slider = [MHGameHotSlider sliderFromNib];
            [self.slider.infiSlider setInfiniteDelegate:self];
            
            NSMutableArray* viewsArray = [[NSMutableArray alloc] init];
            for (Application* app in self.hotData) {
                [viewsArray addObject:[Contants getImageUrl:app.imagePath width:320 height:120]];
            }
            [self.slider.infiSlider setViewsArray:viewsArray];
            [cell.contentView addSubview:self.slider];
        }
        [self.slider removeFromSuperview];
        [cell addSubview:self.slider];
        
        return cell;
    }
    else {
        if (indexPath.row == 0) {
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            if (!cell) {
                cell = [[UITableViewCell alloc] init];
                [cell addSubview:self.listGameView];
            }
            [cell setNeedsDisplay];
            [cell layoutIfNeeded];
            return cell;
        }
        else {
            MHGameCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
            if (!cell) {
                cell = [MHGameCell cellFromNib];
            }
            // configure cell
            Application* app = [self.data objectAtIndex:indexPath.row - 1];
            [cell setApp:app];
            
            return cell;
        }
    }
}


//- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView* view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"View"];
//    if (!view) {
//        if (section == 1) {
//            view = self.listGameView;
//        } else
//        {
//            view = [[UIView alloc] init];
//        }
//    }
//    return view;
//}
//
//
//- (float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    if (section == 1) {
//        return 32;
//    }
//    return 0;
//}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 130;
    }
    if (indexPath.row == 0) {
        return 32;
    }
    return 85;
}


#pragma mark - UITabelView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        MHGameDetailViewController* vc = [[MHGameDetailViewController alloc] initWithNibName:@"MHGameDetailViewController" bundle:nil];
        Application* app = [self.data objectAtIndex:indexPath.row - 1];
        vc.appId = app.appId.integerValue;
        vc.app = app;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - InfiniteScroll delegate
- (void)infiniteScroll:(InfiniteScrollPicker *)picker didSelectedAtIndex:(int)index {
    if (self.hotData.count > index) {
        Application* app = [self.hotData objectAtIndex:index];
        MHGameDetailViewController* vc = [[MHGameDetailViewController alloc] initWithNibName:@"MHGameDetailViewController" bundle:nil];
        vc.appId = app.appId.integerValue;
        vc.app = app;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

//

- (IBAction)gameButtonPressed:(id)sender {
    MHGameListViewController* vc = [[MHGameListViewController alloc] initWithNibName:@"MHGameListViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)appButtonPressed:(id)sender {
    MHAppListViewController* vc = [[MHAppListViewController alloc] initWithNibName:@"MHAppListViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (IBAction)newGameAppButtonPressed:(id)sender {
    MHNewGameAppViewController* vc = [[MHNewGameAppViewController alloc] initWithNibName:@"MHNewGameAppViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (IBAction)eventButtonPressed:(id)sender {
    if ([Lib isUserLogin]) {
        MHGiftViewController* vc = [[MHGiftViewController alloc] initWithNibName:@"MHGiftViewController" bundle:Nil];
        //    [self presentViewController:vc animated:YES completion:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        [Lib showMessage:@"Bạn phải đăng nhập để sử dụng chức năng này!" title:@""];
    }
}


@end
